package com.xlserver.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xlserver.dao.*;
import com.xlserver.domain.*;
import com.xlserver.util.TimeUtil;
import com.xlserver.util.TokenUtil;
import com.xlserver.util.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SupervisorService {
    @Autowired
    ConsultationMapper consultationMapper;

    @Autowired
    LoginInfoMapper loginInfoMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SupervisorMapper supervisorMapper;

    @Autowired
    CounselorMapper counselorMapper;

    @Autowired
    TimeUtil timeUtil;

    @Autowired
    ScheduleService scheduleService;

    @Autowired
    StateMapper stateMapper;

    @Autowired
    SupervisorBandCounselorMapper supervisorBandCounselorMapper;
    /**
     * 修改督导个人信息
     */
    public boolean updateInfo(UserInfo info){
        UpdateWrapper<Supervisor> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("sid",info.getUserId())
                .set("sProfilePhoto",info.getPhotoAddress())
                .set("sName",info.getName())
                .set("sGender",info.getGender())
                .set("sAge",info.getAge())
                .set("sIdNumber",info.getIdNumber())
                .set("sPhoneNum",info.getPhoneNum())
                .set("sEmail",info.getEmail());
        return supervisorMapper.update(null,updateWrapper) == 1;
    }
    /**
     *获取督导信息
     */
    public JSONObject getUserInfo(String username, String password) throws ParseException {
        JSONObject res = new JSONObject();
        if (!checkUsername(username)){
            res.put("result","1");
            return res;
        }
        QueryWrapper<Supervisor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sUsername",username);
        Supervisor supervisor = supervisorMapper.selectOne(queryWrapper);
        if (!checkPassword(supervisor.getSid(),password)){
            res.put("result","2");
            return res;
        }
        Date date = new Date();
        res.put("result","3");
        res.put("id",supervisor.getSid());
        res.put("username",supervisor.getUsername());
        res.put("name",supervisor.getName());
        res.put("todayStatus",scheduleService.getPersonTodayStatus(supervisor.getSid()));
//        res.put("isFree",timeUtil.isFree(supervisor.getSid()));
        res.put("profilePhoto",supervisor.getProfilePhoto());
        res.put("sumOfConsultation",timeUtil.sumOfConsultation(supervisor.getSid()));
        res.put("weekSchedule",scheduleService.getSupervisorWeekSchedule(supervisor.getSid(),date));
        //获取绑定的在线咨询师
        res.put("onlineBandCounselor",getOnlineCounselors(supervisor.getSid()));
        res.put("sumOfConsultationToday",timeUtil.sumOfConsultationToday(supervisor.getSid()));
        res.put("timeOfConsultationToday",timeUtil.timeOfConsultationToday(supervisor.getSid()));
//        res.put("assistsCompleted",supervisor.getAssistanceCompleted());//已完成的咨询
        res.put("theLastFour",lastConsultations(supervisor.getSid()));
        res.put("token", TokenUtil.sign(""+supervisor.getSid(),password));
        //在线
        stateMapper.update(null,new UpdateWrapper<State>().eq("id",supervisor.getSid()).set("state",0));
        return res;
    }
    /**
     * 获取所有会话
     */
    public JSONArray getAllMsgs(int id){
        JSONArray res = new JSONArray();
        consultationMapper.selectList(new QueryWrapper<Consultation>().eq("cid",id)).
                forEach(consultation -> {
                    JSONObject msg = new JSONObject();
                    msg.put("id",consultation.getHid());
                    msg.put("name",counselorMapper.selectById(consultation.getUid()).getName());
                    try {
                        msg.put("time",timeUtil.getTimeDiff(consultation));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    msg.put("beginTime",consultation.getBeginTime());
                    res.add(msg);
                });
        return res;
    }
    /**
     * 根据咨询师姓名模糊查询会话
     */
    public JSONArray getAllMsgsByName(int id,String name){
        JSONArray res = new JSONArray();
        List<Counselor> counselors = counselorMapper.selectList(
                new QueryWrapper<Counselor>().eq("cName",name));
        if (counselors.size() == 0){
            return res;
        }
        counselors.forEach(counselor -> {
            List<Consultation> consultations = consultationMapper.selectList(
                    new QueryWrapper<Consultation>().
                            eq("uid",counselor.getCid()).
                            eq("cid",id));
            consultations.forEach(consultation -> {
                JSONObject msg = new JSONObject();
                msg.put("name",name);
                msg.put("id",consultation.getHid());
                try {
                    msg.put("time",timeUtil.getTimeDiff(consultation));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                msg.put("beginTime",consultation.getBeginTime());
                res.add(msg);
            });
        });
        return res;
    }
    /**
     * 判断username是否有效
     */
    private boolean checkUsername(String username){
        QueryWrapper<Supervisor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sUsername",username);
        return supervisorMapper.selectList(queryWrapper).size() != 0;
    }
    /**
     *判断密码是否正确
     */
    private boolean checkPassword(int id,String password){
        QueryWrapper<LoginInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return password.equals(loginInfoMapper.selectList(queryWrapper).get(0).getPassword());
    }
    /**
     * 获取最近四条聊天记录
     */
    public JSONArray lastConsultations(int cid) throws ParseException {
        JSONArray res = new JSONArray();
        QueryWrapper<Consultation> queryWrapper = new QueryWrapper<Consultation>().
                eq("cid",cid).
                orderByDesc("h_beginTime").
                last("limit 4");
        List<Consultation> consultations = consultationMapper.selectList(queryWrapper);
        for (Consultation consultation: consultations) {
            JSONObject ret = new JSONObject();
            ret.put("id",consultation.getHid());
            ret.put("name",counselorMapper.selectById(consultation.getUid()).getName());
            ret.put("time",timeUtil.getTimeDiff(consultation));
            ret.put("beginTime",consultation.getBeginTime());
            res.add(ret);
        }
        return res;
    }
    /**
     * 根据id获得督导信息
     * 头像，姓名，性别，年龄，身份证，电话，邮箱
     */
    public JSONObject getCounselorInfo(int id){
        Supervisor supervisor = supervisorMapper.selectById(id);
        JSONObject ret = new JSONObject();
        ret.put("avatar",supervisor.getProfilePhoto());
        ret.put("name",supervisor.getName());
        ret.put("gender",supervisor.getGender());
        ret.put("age",supervisor.getAge());
        ret.put("idNumber",supervisor.getIdNumber());
        ret.put("phoneNum",supervisor.getPhoneNum());
        ret.put("email",supervisor.getEmail());
        return ret;
    }
    /**
     * 获取上线的咨询师（名字，是否空闲）
     */
    public JSONArray getOnlineCounselors(int sid){
        JSONArray res = new JSONArray();
        stateMapper.selectList(new QueryWrapper<State>().eq("state",0)).forEach(state -> {
            if (state.getId()<30000 && state.getId() >= 20000 && supervisorBandCounselorMapper
                    .selectOne(new QueryWrapper<SupervisorBandCounselor>()
                            .eq("sid",sid)
                            .eq("cid",state.getId())) != null){
                Counselor counselor = counselorMapper.selectById(state.getId());
                JSONObject ret = new JSONObject();
                ret.put("name",counselor.getName());
                ret.put("isFree",timeUtil.isFree(counselor.getCid()));
                res.add(ret);
            }
        });
        return res;
    }










}
